﻿Imports Runa.Foundation.Messaging
Imports System.Threading.Tasks
Imports Runa.Common.Helper
Imports System.Collections.Concurrent

Namespace Threading

    Public NotInheritable Class Thread
        Implements IMessageQueue

        Public Property ThreadID() As Integer
        Public Property Task() As Task

        Private m_parameter As Object = Nothing

        Private m_threadMessageQueue As New ConcurrentQueue(Of Message)

        Protected Friend ReadOnly Property ThreadMessageQueue() As ConcurrentQueue(Of Message) Implements IMessageQueue.MessageQueue
            Get
                Return Me.m_threadMessageQueue
            End Get
        End Property

        Public Shared ReadOnly Property CurrentThread() As Thread
            Get
                Return Thread.FromThread(GetCurrentThreadId())
            End Get
        End Property

        Public ReadOnly Property IsCompleted() As Boolean
            Get
                Return Me.Task.IsCompleted
            End Get
        End Property

        Public Sub New(ByVal start As Action)
            Me.Task = New Task(Sub() start())
            Me.ThreadID = Me.Task.Id
            ThreadPool.ThreadPool.TryAdd(Me.ThreadID, Me)
        End Sub

        Public Sub New(ByVal start As Action(Of Object), ByVal state As Object)
            Me.m_parameter = state
            Me.Task = New Task(New Action(Of Object)(Sub(obj) start(obj)), Me.m_parameter)
            Me.ThreadID = Me.Task.Id
            ThreadPool.ThreadPool.TryAdd(Me.ThreadID, Me)
        End Sub

        Public Sub New(ByVal tid As Integer)
            Me.ThreadID = tid
            Dim td As Thread
            If ThreadPool.ThreadPool.ContainsKey(tid) Then
                td = ThreadPool.FromThread(tid)
                With Me
                    .m_parameter = td.m_parameter
                    .Task = td.Task
                End With
            Else
                ThreadPool.ThreadPool.TryAdd(Me.ThreadID, Me)
            End If
        End Sub

        Public Sub Start()
            Me.Task.Start()
        End Sub

        Public Sub Start(ByVal state As Object)
            Me.Task.Start(state)
        End Sub

        Public Shared Function FromThread(ByVal tid As Integer) As Thread
            If ThreadPool.ThreadPool.ContainsKey(tid) Then
                Return ThreadPool.ThreadPool(tid)
            Else
                Return New Thread(tid)
            End If
        End Function

    End Class

End Namespace